package rbac.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import rbac.dao.RoleDao;
import rbac.entity.RbacRole;


/**
 * RBAC 角色管理 DAO 实现类.
 * 
 * @author Huadi
 * @author Zoufengyang
 */
@Repository("roleDao")
public class RoleDaoImpl extends HibernateDaoSupport implements RoleDao {

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
	public void delete(RbacRole role) {
		// XXX: 删除关系表中的实体关系记录, 此处与实体表耦合.
		Query query = getSession().createSQLQuery(
				"DELETE FROM t_rbac_group_role WHERE role_id = :id");
		query.setInteger("id", role.getId());
		query.executeUpdate();
		getHibernateTemplate().delete(role);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
	public void delete(Integer roleId) {
		// XXX: 删除关系表中的实体关系记录, 此处与实体表耦合.
		Query q = getSession().createSQLQuery(
				"DELETE FROM t_rbac_group_role WHERE role_id = :id");
		q.setInteger("id", roleId);
		q.executeUpdate();
		Query query = getSession().getNamedQuery("rbacRole.deleteRbacRoleById");
		query.setInteger("id", roleId);
		query.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
	public List<RbacRole> getAllRoles() {
		Query query = getSession().getNamedQuery("rbacRole.getAllRbacRoles");
		return query.list();
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
	public RbacRole getRole(Integer id) {
		return (RbacRole) getHibernateTemplate().get(RbacRole.class, id);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
	public Integer save(RbacRole role) {
		return (Integer) getHibernateTemplate().save(role);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor={Exception.class})
	public void update(RbacRole role) {
		getHibernateTemplate().update(role);
	}

}
